//
//  VersionManager.swift
//  XueDao
//
//  Created by wenwen on 2021/5/18.
//

import UIKit
import StoreKit

let IgnoreCurrentVersionUpdate = "IgnoreCurrentVersionUpdate"

class XD_VersionModel: XS_BaseModel {
    var state = "" // 是否强制更新
    var code = "" // 版本
    var details = "" // 提示内容
}

class VersionManager: NSObject {
    static func checkVersion(rootVc: UIViewController) {
        XS_NetWork.requestJson("/sysEdition/queryNewEdition", parameters: ["systemType" : "iOS"])
            .mapModel(type: XD_VersionModel.self)
            .subscribe(onNext: { (models, res) in
                guard let model = models, res.success else { return }
                handleUpdate(rootVC: rootVc, model: model)
            })
    }
}

extension VersionManager {
    /// 本地版本
    private static func localVersion() -> String? {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    }
    
    /// 版本比较
    private static func versionCompare(localVersion: String, serverVersion: String) -> Bool {
        let result = localVersion.compare(serverVersion, options: .numeric, range: nil, locale: nil)
        if result == .orderedDescending || result == .orderedSame{
            return false
        }
        return true
    }
    
    /// 是否忽略当前版本更新
    private static func isIgnoreCurrentVersionUpdate(version: String) -> Bool {
        return UserDefaults.standard.string(forKey: IgnoreCurrentVersionUpdate) == version
    }
    
    private static func handleUpdate(rootVC: UIViewController, model: XD_VersionModel) {
//        UserDefaults.standard.removeObject(forKey: IgnoreCurrentVersionUpdate)
        guard let localVersion = localVersion() else { return }
        if isIgnoreCurrentVersionUpdate(version: model.code) { return }
        if versionCompare(localVersion: localVersion, serverVersion: model.code) {
            let versionVC = VersionManagerVC()
            versionVC.modalPresentationStyle = .overCurrentContext
            versionVC.dataModel = model
            rootVC.present(versionVC, animated: true, completion: nil)
        }
    }
}

fileprivate class VersionManagerVC: UIViewController {
    lazy var dataModel = XD_VersionModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = UIColor(red: 0.15, green: 0.15, blue: 0.16, alpha: 0.40)
        
        initViews()
    }
    
    func initViews() {
        let bgView = UIView()
        bgView.layer.cornerRadius = .scale * 8
        bgView.layer.masksToBounds = true
        bgView.backgroundColor = .white
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.equalTo(.scale * 48)
            make.right.equalTo(-.scale * 48)
            make.centerY.equalToSuperview()
        }
        
        let imgV = UIImageView()
        imgV.image = UIImage.init(named: "upVersion")
        bgView.addSubview(imgV)
        imgV.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        let cancelBtn = UIButton.init(type: .custom)
        cancelBtn.isHidden = false
        cancelBtn.titleLabel?.font = .systemFont(ofSize: .scale * 14, weight: .regular)
        cancelBtn.backgroundColor = .white
        cancelBtn.layer.cornerRadius = .scale * 20
        cancelBtn.layer.masksToBounds = true
        cancelBtn.setTitleColor(UIColor(red: 0.67, green: 0.69, blue: 0.72, alpha: 1.00), for: .normal)
        cancelBtn.setTitle("以后再说", for: .normal)
        cancelBtn.addTarget(self, action: #selector(cancelDiss), for: .touchUpInside)
        bgView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.left.equalTo(.scale * 21)
            make.right.equalTo(-.scale * 21)
            make.bottom.equalTo(-.scale * 3)
            make.height.equalTo(.scale * 40)
        }
        
        let updateBtn = UIButton.init(type: .custom)
        updateBtn.titleLabel?.font = .systemFont(ofSize: .scale * 16, weight: .medium)
        updateBtn.backgroundColor = UIColor(red: 0.16, green: 0.74, blue: 0.61, alpha: 1.00)
        updateBtn.layer.cornerRadius = .scale * 20
        updateBtn.layer.masksToBounds = true
        updateBtn.setTitleColor(.white, for: .normal)
        updateBtn.setTitle("立即更新", for: .normal)
        updateBtn.addTarget(self, action: #selector(updateVersion), for: .touchUpInside)
        bgView.addSubview(updateBtn)
        updateBtn.snp.makeConstraints { make in
            make.left.equalTo(.scale * 21)
            make.right.equalTo(-.scale * 21)
            make.bottom.equalTo(cancelBtn.snp.top)
            make.height.equalTo(.scale * 40)
        }
        
        let isForce = dataModel.state == "force"
        if isForce {
            cancelBtn.isHidden = isForce
            cancelBtn.snp.updateConstraints { make in
                make.height.equalTo(0)
            }
            updateBtn.snp.updateConstraints { make in
                make.bottom.equalTo(cancelBtn.snp.top).offset(-.scale * 12)
            }
        }
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 5
        let attributesDict = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: .scale * 14, weight: .regular),
                              .paragraphStyle : paragraphStyle,
                              .foregroundColor : UIColor(red: 0.45, green: 0.47, blue: 0.49, alpha: 1.00)]
        
        let attributedStr = NSAttributedString.init(string: dataModel.details, attributes: attributesDict)
        
        var descTextVHeight = attributedStr.boundingRect(with: CGSize.init(width: UIScreen.main.bounds.size.width - (.scale * 48 * 2 + .scale * 21 * 2), height: CGFloat(MAXFLOAT)), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil).size.height
        
        if descTextVHeight > 141 {
            descTextVHeight = 141
        }

        let descTextV = UITextView()
        descTextV.textContainer.lineFragmentPadding = 0
        descTextV.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        descTextV.isEditable = false
        descTextV.isSelectable = false
        descTextV.isScrollEnabled = true
        descTextV.showsVerticalScrollIndicator = true
        descTextV.showsHorizontalScrollIndicator = false
        descTextV.attributedText = attributedStr
        bgView.addSubview(descTextV)
        descTextV.snp.makeConstraints { make in
            make.top.equalTo(imgV.snp.bottom)
            make.left.equalTo(.scale * 21)
            make.right.equalTo(-.scale * 21)
            make.bottom.equalTo(updateBtn.snp.top).offset(-.scale * 15)
            make.height.equalTo(.scale * descTextVHeight)
        }
    }
}

extension VersionManagerVC {
    @objc func updateVersion() {
        let storeVC = SKStoreProductViewController()
        storeVC.delegate = self
        storeVC.loadProduct(withParameters:[SKStoreProductParameterITunesItemIdentifier: "1546417779"], completionBlock: { (result, error) in
            if !result {
                storeVC.dismiss(animated: true, completion: nil)
            }
        })
        self.present(storeVC, animated: true, completion: nil)
    }
    
    @objc func cancelDiss() {
        UserDefaults.standard.set(dataModel.code, forKey: IgnoreCurrentVersionUpdate)
        self.dismiss(animated: true, completion: nil)
    }
}

extension VersionManagerVC: SKStoreProductViewControllerDelegate {
    func productViewControllerDidFinish(_ viewController: SKStoreProductViewController) {
        viewController.dismiss(animated: true, completion: nil)
    }
}
